package com.jinlia.show.modules.openservice.service;

import com.alibaba.fastjson.JSON;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ScheduledExecutorService;

@Slf4j
@Service
public class AliyunSmsService {

    @Autowired
    AsyncClient asyncClient;
    @Autowired
    ScheduledExecutorService scheduledExecutorService;
    Random random = new Random();
    /**
     * 发送短信
     */
    /**
     * @param signName      签名
     * @param templateCode  模板id(code)
     * @param phoneNumbers  手机号
     * @param templateParam 模板参数
     */
    @SneakyThrows
    public void sendSms(String signName, String templateCode, String phoneNumbers, String templateParam) {
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName(signName)
                .templateCode(templateCode)
                .phoneNumbers(phoneNumbers)
                .templateParam(templateParam)
                .build();
        log.info("aliyun sms sendSmsRequest = {}", JSON.toJSONString(sendSmsRequest));
        scheduledExecutorService.submit(() -> {
            CompletableFuture<SendSmsResponse> response = asyncClient.sendSms(sendSmsRequest);
            try {
                SendSmsResponse resp = response.get();
                log.info("aliyun sms sendSmsResponse:{}", JSON.toJSONString(resp));
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        });


    }
}
